package com.ocm.core.util;

import java.util.Iterator;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import com.ocm.core.domain.PropertyDefinition;
import com.ocm.core.model.ClassInstance;

public class JSONUtil {

   private final static ClassInstancePropertyFilter classInstancePropertyFilter = new ClassInstancePropertyFilter();

   private final static PropertyDefinitionPropertyFilter propertyDefinitionPropertyFilter = new PropertyDefinitionPropertyFilter();

   public static JSONObject convertToObject(ClassInstance classInstance){
      JsonConfig propertyJsonConfig = new JsonConfig();
      propertyJsonConfig.setJsonPropertyFilter(propertyDefinitionPropertyFilter);
      
      JsonConfig jsonConfig = new JsonConfig();
      jsonConfig.setJsonPropertyFilter(classInstancePropertyFilter);
      JSONObject jsonObject = JSONObject.fromObject(classInstance, jsonConfig);
      Map<PropertyDefinition, Object> properties = classInstance.getProperties();
      JSONObject jsonProperties = new JSONObject();
      JSONArray jsonArray = new JSONArray();
      for (Iterator<PropertyDefinition> it = properties.keySet().iterator(); it.hasNext();){
         PropertyDefinition propertyDefinition = it.next();
         JSONObject jsonProperty = JSONObject.fromObject(propertyDefinition, propertyJsonConfig);
         jsonArray.add(jsonProperty);
         jsonProperties.put(propertyDefinition.getName(), properties.get(propertyDefinition));
      }
      jsonProperties.put("properties", jsonArray);
      jsonObject.put("propertiesValue", jsonProperties);
      return jsonObject;
   }
}

class ClassInstancePropertyFilter implements PropertyFilter{
   public boolean apply(Object source, String name, Object value) {
      if ("properties".equals(name) || "createdUser".equals(name) || "createdDated".equals(name) || "modifyedUser".equals(name) || "modifyedDated".equals(name)){
         return true;
      }
      return false;
   }
}

class PropertyDefinitionPropertyFilter implements PropertyFilter{
   public boolean apply(Object source, String name, Object value) {
      if ("status".equals(name) || "storage".equals(name) || "version".equals(name) 
            || "createdUser".equals(name) || "createdDated".equals(name) || "modifyedUser".equals(name) || "modifyedDated".equals(name)){
         return true;
      }
      return false;
   }
}